package cn.wen233.srpc.basic.utils;

import java.io.File;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * Class 文件工具类
 *
 * @author wenei
 * @date 2021-10-27 17:11
 */
public class ClassUtils {

    private static final ClassLoader loader = Thread.currentThread().getContextClassLoader();

    private static final String META_INF = "META-INF";

    public static Set<Class<?>> findAllClasses(String packageName) {
        Set<Class<?>> classSet = new HashSet<>();
        // 通过ClassLoader获取绝对路径
        URL rootURL = loader.getResource(packageName.replace(".", "/"));
        File rootFile = new File(rootURL.getFile());
        for (File file : rootFile.listFiles()) {
            if (META_INF.equals(file.getName())) {
                continue;
            }
            findClass(file, packageName, classSet);
        }
        return classSet;
    }

    private static void findClass(File file, String packageName, Set<Class<?>> classSet) {
        if (file.isFile()) {
            try {
                String classSimpleName = file.getName().substring(0, file.getName().lastIndexOf("."));
                Class<?> clazz = loader.loadClass(packageName + "." + classSimpleName);
                classSet.add(clazz);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            for (File subFile : file.listFiles()) {
                String nextPackage = packageName + "." + file.getName();
                if (nextPackage.startsWith(".")) {
                    nextPackage = nextPackage.substring(1);
                }
                findClass(subFile, nextPackage, classSet);
            }
        }
    }
}
